// 一杆云枢 - 台球场馆管理系统后端API
const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const rateLimit = require('express-rate-limit');
const path = require('path');
require('dotenv').config();

// 导入数据库配置
const { testConnection, closePool } = require('./config/database');

// 导入路由
const authRoutes = require('./routes/auth');
const userRoutes = require('./routes/users');
const adminRoutes = require('./routes/admin');
const tableRoutes = require('./routes/tables');
const orderRoutes = require('./routes/orders');
const paymentRoutes = require('./routes/payment');
const financeRoutes = require('./routes/finance');
const inventoryRoutes = require('./routes/inventory');
const announcementRoutes = require('./routes/announcements');

// 导入工具
const ResponseHelper = require('./utils/response');

// 创建Express应用
const app = express();
const PORT = process.env.PORT || 3001;

// 安全中间件
app.use(helmet({
  crossOriginResourcePolicy: { policy: "cross-origin" }
}));

// CORS配置
app.use(cors({
  origin: ['http://localhost:8080', 'http://localhost:8081', 'http://localhost:8082'], // 支持本地前端地址
  credentials: true
}));

// 速率限制
const limiter = rateLimit({
  windowMs: (parseInt(process.env.RATE_LIMIT_WINDOW) || 15) * 60 * 1000, // 15分钟
  max: parseInt(process.env.RATE_LIMIT_MAX) || 100, // 限制每个IP 100个请求
  message: {
    success: false,
    message: '请求过于频繁，请稍后再试'
  },
  standardHeaders: true,
  legacyHeaders: false
});

app.use('/api/', limiter);

// 解析JSON和URL编码的请求体
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));

// 静态文件服务（用于头像等文件上传）
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

// 请求日志中间件
app.use((req, res, next) => {
  if (process.env.NODE_ENV === 'development') {
    const timestamp = new Date().toISOString();
    console.log(`[${timestamp}] ${req.method} ${req.url} - IP: ${req.ip}`);
  }
  next();
});

// 健康检查端点
app.get('/api/health', (req, res) => {
  ResponseHelper.success(res, {
    status: 'healthy',
    timestamp: new Date().toISOString(),
    version: '2.1.0',
    environment: process.env.NODE_ENV || 'development'
  }, '服务运行正常');
});

// API路由
app.use('/api/auth', authRoutes);
app.use('/api/user', userRoutes);
app.use('/api/admin', adminRoutes);
app.use('/api/tables', tableRoutes);
app.use('/api/orders', orderRoutes);
app.use('/api/payment', paymentRoutes);
app.use('/api/finance', financeRoutes);
app.use('/api/inventory', inventoryRoutes);
app.use('/api/announcements', announcementRoutes);

// 根路径
app.get('/', (req, res) => {
  res.json({
    name: '一杆云枢 API',
    version: '2.1.0',
    description: '台球场馆管理系统后端API',
    author: 'levi',
    endpoints: {
      health: '/api/health',
      auth: '/api/auth',
      user: '/api/user',
      admin: '/api/admin',
      tables: '/api/tables',
      orders: '/api/orders',
      payment: '/api/payment',
      finance: '/api/finance',
      inventory: '/api/inventory',
      announcements: '/api/announcements'
    }
  });
});

// 404处理
app.use('*', (req, res) => {
  ResponseHelper.notFound(res, `接口 ${req.originalUrl} 不存在`);
});

// 全局错误处理中间件
app.use((error, req, res, next) => {
  console.error('全局错误处理:', error);

  // Multer文件上传错误
  if (error.code === 'LIMIT_FILE_SIZE') {
    return ResponseHelper.error(res, '文件大小超出限制', 400);
  }

  if (error.code === 'LIMIT_UNEXPECTED_FILE') {
    return ResponseHelper.error(res, '意外的文件字段', 400);
  }

  // JWT错误
  if (error.name === 'JsonWebTokenError') {
    return ResponseHelper.unauthorized(res, '无效的访问令牌');
  }

  if (error.name === 'TokenExpiredError') {
    return ResponseHelper.unauthorized(res, '访问令牌已过期');
  }

  // 数据库错误
  if (error.code === 'ER_DUP_ENTRY') {
    return ResponseHelper.error(res, '数据已存在，请检查唯一性约束', 400);
  }

  if (error.code === 'ER_NO_REFERENCED_ROW_2') {
    return ResponseHelper.error(res, '引用的数据不存在', 400);
  }

  // 验证错误
  if (error.type === 'entity.parse.failed') {
    return ResponseHelper.error(res, '请求数据格式错误', 400);
  }

  // 默认服务器错误
  ResponseHelper.serverError(res,
    process.env.NODE_ENV === 'development' ? error.message : '服务器内部错误'
  );
});

// 启动服务器
async function startServer() {
  try {
    console.log('正在测试数据库连接...');
    const dbConnected = await testConnection();

    if (!dbConnected) {
      console.warn('数据库连接失败，将以无数据库模式启动');
      console.warn('部分功能可能不可用，请检查数据库配置');
    }

    // 启动HTTP服务器
    const server = app.listen(PORT, () => {
      console.log('一杆云枢后端服务启动成功!');
      console.log(`服务器运行在: http://localhost:${PORT}`);
      console.log(`API文档: http://localhost:${PORT}/api/health`);
      console.log(`环境: ${process.env.NODE_ENV || 'development'}`);
      console.log(`数据库状态: ${dbConnected ? '已连接' : '未连接'}`);
      console.log('可用的API端点:');
      console.log('   - 认证: /api/auth');
      console.log('   - 用户: /api/user');
      console.log('   - 管理: /api/admin');
      console.log('   - 台球桌: /api/tables');
      console.log('   - 订单: /api/orders');
      console.log('   - 支付: /api/payment');
      console.log('   - 财务: /api/finance');
      console.log('   - 库存: /api/inventory');
      console.log('   - 公告: /api/announcements');
    });

    // 优雅关闭处理
    const gracefulShutdown = async (signal) => {
      console.log(`\n收到 ${signal} 信号，正在优雅关闭服务器...`);

      server.close(async () => {
        console.log('HTTP服务器已关闭');

        // 关闭数据库连接池
        await closePool();

        console.log('服务器已完全关闭');
        process.exit(0);
      });

      // 强制关闭超时
      setTimeout(() => {
        console.error('强制关闭服务器');
        process.exit(1);
      }, 10000);
    };

    // 监听关闭信号
    process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
    process.on('SIGINT', () => gracefulShutdown('SIGINT'));

  } catch (error) {
    console.error('❌ 服务器启动失败:', error);
    process.exit(1);
  }
}

// 启动服务器
startServer();

require('./scheduler/releaseTables');
